package com.clip.dao;

// default package

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.springframework.stereotype.Repository;

import com.clip.entity.Contact;
import com.clip.entity.User;
import com.clip.util.ToolsUtils;


@Repository
public class ContactDAO extends BasicDao  {
    private static final Log log = LogFactory.getLog(ContactDAO.class);
	//property constants

	public static final String UID = "uid";
	public static final String NAME = "name";
	public static final String CONTACTTYPEID = "contacttypeid";
	public static final String CONTACTEMAIL = "contactemail";

	public void save(Contact transientInstance) {
		log.debug("saving Contact instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(Contact persistentInstance) {
		log.debug("deleting Contact instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Contact findById(java.lang.Integer id) {
		log.debug("getting Contact instance with id: " + id);
		try {
			Contact instance = (Contact) getSession().get(Contact.class, id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<Contact> findByExample(Contact instance) {
		log.debug("finding Contact instance by example");
		try {
			List<Contact> results = this.getSession().createCriteria(Contact.class).add(Example.create(instance)).list();
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Contact instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from Contact as model where model." + propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUid(Object uid) {
		return findByProperty(UID, uid);
	}

	public List findByName(Object name) {
		return findByProperty(NAME, name);
	}

	public List findByContacttypeid(Object contacttypeid) {
		return findByProperty(CONTACTTYPEID, contacttypeid);
	}
	public List findByContactEmail(Object email){
		return findByProperty(CONTACTEMAIL, email);
	}

	public List findAll() {
		log.debug("finding all Contact instances");
		try {
			String queryString = "from Contact";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Contact merge(Contact detachedInstance) {
		log.debug("merging Contact instance");
		try {
			Contact result = (Contact) getSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Contact instance) {
		log.debug("attaching dirty Contact instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Contact instance) {
		log.debug("attaching clean Contact instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
	public List findByQuery(String query) {
		return findByQuery(query,null);
	}
	
	public List findByQuery(String query,Object ... args) {
		Query queryobj=getSession().createQuery(query);
		if(args!=null&&args.length>0){
			for (int i = 0; i < args.length; i++) {
				queryobj.setParameter(i, args[i]);
			}
		}
		return queryobj.list();
	}
	
	public long countByQuery(String query){
		return (Long) getSession().createQuery(query).uniqueResult();
		
	}
	
	public List pagingByQuery(String queryStr, Integer currentpage,
			Integer pagesize) {
		Query query =getSession().createQuery(queryStr);
		query.setMaxResults(pagesize);
		query.setFirstResult(currentpage*pagesize);
		return query.list();
	}
	
	public void deleteByQuery(String query) {
		getSession().createQuery(query).executeUpdate();
	}
	/**
	 * 添加2个用户互相为联系人
	 * @param user		用户1
	 * @param otherUser	用户2
	 * @param email		联系人EMAIL 可以为空
	 * @return
	 */
	public boolean addFriend(User user,User otherUser,String email){
		Contact c1 = null;
		Contact c2 = null;
		String hql = "SELECT c FROM Contact c WHERE (c.contactemail='"+email+"' OR c.contactemail='"+user.getEmail()+"') AND c.uid="+otherUser.getId()+" AND (c.contactuid=0 OR c.contactuid="+user.getId()+")";
		//查询otherUser 是否添加user为联系人
		List<Contact> cList = this.getSession().createQuery(hql).list();
		c1 = cList!=null&&cList.size()>0 ? cList.get(0) : null;
		if(c1!=null){
			c1.setContactuid(user.getId());
			c1.setStatus(1);
			c1.setContactemail(user.getEmail());
			//c1.setName(user.getName());
			//c1.setPinyinname(ToolsUtils.chinese2pinyin(user.getName()));
			c1.setContacttypeid(c1.getContacttypeid()==4||c1.getContacttypeid()==0 ? 1 : c1.getContacttypeid());
			this.attachDirty(c1);
		}else{
			c1 = new Contact();
			c1.setUid(otherUser.getId());
			c1.setContactuid(user.getId());
			c1.setContactemail(user.getEmail());
			c1.setName(user.getName());
			c1.setPinyinname(ToolsUtils.chinese2pinyin(user.getName()));
			c1.setContacttypeid(1);
			c1.setStatus(1);
			this.save(c1);
		}
		if(!user.getEmail().equals(email)){
			hql = "DELETE FROM Contact c WHERE c.contactemail='"+email+"' AND c.uid="+otherUser.getId()+" AND (c.contactuid=0 OR c.contactuid="+user.getId()+")";
			this.deleteByQuery(hql);
		}
		if(c1!=null){
			hql = "SELECT c FROM Contact c WHERE c.uid="+user.getId()+" AND c.contactuid="+otherUser.getId()+" AND c.contactemail='"+otherUser.getEmail()+"'";
			List<Contact> list = this.getSession().createQuery(hql).list();
			c2 = list!=null&&list.size()>0 ? list.get(0) : null;
			if(c2!=null){
				c2.setStatus(1);
				c2.setContacttypeid(1);
				c2.setContacttypeid(c2.getContacttypeid()==4 ? 1 : c2.getContacttypeid());
				this.attachDirty(c2);
			}else{
				c1 = new Contact();
				c1.setUid(user.getId());
				c1.setContactuid(otherUser.getId());
				c1.setContactemail(otherUser.getEmail());
				c1.setName(otherUser.getName());
				c1.setPinyinname(ToolsUtils.chinese2pinyin(otherUser.getName()));
				c1.setContacttypeid(1);
				c1.setStatus(1);
				this.save(c1);
			}
		}else{
			return false;
		}
		return true;
	}
	/**
	 * 移除2个用户互相为联系人
	 * @param user		用户1
	 * @param otherUser	用户2
	 * @param email		联系人EMAIL 可以为空
	 * @return
	 */
	public void unFriend(User user,User otherUser,String email){
		String hql="DELETE FROM Contact c where (c.uid="+otherUser.getId()+" and c.contactemail='"+email+"') or (c.uid="+user.getId()+" and c.contactuid="+otherUser.getId()+") or (c.uid="+otherUser.getId()+" and c.contactuid="+user.getId()+")";
		this.getSession().createQuery(hql).executeUpdate();
	}
}